#include "ModelLoader.h"
#include "OBJProcessor.h"
#include <sstream>

namespace Caelum {

ModelData::Model *ModelLoader::LoadModel(std::wstring Path)
{
	std::wstring working; //a string to hold the extension as we read it
	std::wstring::const_reverse_iterator it;
	for (it = Path.crbegin(); it != Path.crend(); it++) //read from back of the Path
	{
		if ((*it) == L'.') //if it's a dot, then we're done
			break;
		working = (wchar_t)towlower((*it)) + working;
	}

	try {
		if (working == L"obj")
		{
			return LoadModel(MODELTYPE_OBJ, Path);
		}
		else if (working == L"bin")
		{
			return LoadModel(MODELTYPE_BIN, Path);
		}
		else
		{
			throw new ModelTypeNotSupportedException(L"The model extension \"" + working + L"\" is not supported.");
		}
	} catch (...) {
		throw;
	}
}

ModelData::Model *ModelLoader::LoadModel(ModelType Type, std::wstring Path)
{
	switch (Type)
	{
	case MODELTYPE_BIN:
		{
			throw new NotImplementedException(L"Model type BIN loading not yet implemented. Sorry!");
		}
	case MODELTYPE_OBJ:
		{
			ModelData::OBJProcessor p(Path);
			models.push_back(p.GetModel());
			return p.GetModel();
		}
	default:
		{
			throw new ModelTypeNotSupportedException(L"Invalid model type given!");
		}
	}
	return 0;
}

void ModelLoader::ReleaseModel(ModelData::Model *Mdl)
{
	models.remove(Mdl);
	delete Mdl;
}

}